package Week1.Solution_2;
import java.io.*;

public class MyClassLoader extends ClassLoader{
    /**
     * 指定路径
     */
    private String path;
    private File outputFile;

    public MyClassLoader(String path, File outputFile){
        this.path = path;
        this.outputFile = outputFile;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class log = null;

        // 获取改class文件字节码数组
        byte[] classData = getDate();

        if(classData != null){
            log = defineClass(name,classData,0,classData.length);
        }
        return log;
    }

    /**
     * 将class文件转化为字节码数组
     * */
    private byte[] getDate(){
        File file = new File(path);
        if(file.exists()){
            FileInputStream in = null;
            OutputStream outfile = null;
            byte[] data = null;
            ByteArrayOutputStream out = null;

            try{
                in = new FileInputStream(file);
                outfile = new FileOutputStream(outputFile);
                out = new ByteArrayOutputStream();
                int size = 0;
                while(size != -1){
                    size = in.read();
                    outfile.write(255-size);
                    out.write(255-size);
                }
                data =  out.toByteArray();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try {
                    in.close();
                    outfile.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            return data;
        }else{
            return  null;
        }
    }
}
